#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime>
#include <QVideoWidget>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    init();
    db_init();
    db_select();

    this->setFixedSize(1050,650);
    this->setWindowTitle("绿洲智联");

    tm_time = m_HandWidget->tm_time;
    hm_time = m_HandWidget->hm_time;
    ill_time = m_HandWidget->ill_time;

    get_init();

    connect(m_MonitorWidget,&MonitorWidget::ErrorResetBtn_push,this,&MainWindow::get_token);//连接
    connect(m_MonitorWidget,&MonitorWidget::reset,this,[=](){
        //清零time表
        resetTimeTable();

        //重置AI预测数据
        m_AIPredictionWidget->setEnvironmentData(0, 0, 0);
    });//复位

    connect(m_MonitorWidget,&MonitorWidget::ProductEndBtn_push,this,[=](){
        this->close();
    });//结束

    /*******HTTP连接华为云******/
    manger = new QNetworkAccessManager(this);

    currentCallback = nullptr;

    TOKEN_FILE = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)
               + "/token.dat";
    QDir().mkpath(QFileInfo(TOKEN_FILE).path()); // 确保目录存在

    Token = loadTokenFromFile(); // 启动时自动加载
    if (!Token.isEmpty())
        qDebug() << "Loaded saved token";

    connect(manger, &QNetworkAccessManager::finished, this, &MainWindow::replyFinished);

}

void MainWindow::get_token()
{
    //表示获取token
    function_select = 3;

    QString requestUrl;
    QNetworkRequest request;
    //设置请求地址
    QUrl url;

    //获取token请求地址
    requestUrl = QString("https://iam.%1.myhuaweicloud.com/v3/auth/tokens")
            .arg(SERVER_ID);

    //设置数据提交格式
    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json;charset=UTF-8"));

    //构造请求
    url.setUrl(requestUrl);

    request.setUrl(url);

    QString text = QString("{\"auth\": {\"identity\":{\"methods\":[\"password\"],\"password\":"
    "{\"user\":{\"domain\": {"
    "\"name\":\"%1\"},\"name\": \"%2\",\"password\": \"%3\"}}},"
    "\"scope\":{\"project\":{\"name\":\"%4\"}}}}")
        .arg(MAIN_USER)
        .arg(IAM_USER)
        .arg(IAM_PASSWORD)
        .arg(SERVER_ID);

    qDebug() << "\r\n";
    qDebug() << "text.toUtf8():" << text.toUtf8();
    qDebug() << "\r\n";

    //发送请求
    manger->post(request, text.toUtf8());
}

void MainWindow::sendMessageToDevice(const QJsonObject& contentObj)
{
    QString projectId = "8cf7b43a2a43485da2a4a92c46f955ef";
    QString deviceId = "686cd7c2d582f200183946de_dev1";
    QString endpoint = "https://489fb75c06.st1.iotda-app.cn-north-4.myhuaweicloud.com:443";

    QString url = QString("%1/v5/iot/%2/devices/%3/messages")
                  .arg(endpoint).arg(projectId).arg(deviceId);

    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setRawHeader("X-Auth-Token", Token);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QJsonObject jsonBody;
    jsonBody["message_id"] = QUuid::createUuid().toString().remove('{').remove('}');
    jsonBody["name"] = "DeviceCommand";
    jsonBody["message"] = contentObj;

    QJsonDocument doc(jsonBody);
    manger->post(request, doc.toJson());
}

void MainWindow::getDeviceProperties(std::function<void(const QJsonObject&, int)> callback)
{
    QString projectId = "8cf7b43a2a43485da2a4a92c46f955ef";
    QString deviceId = "686cd7c2d582f200183946de_dev1";
    QString baseUrl = "https://489fb75c06.st1.iotda-app.cn-north-4.myhuaweicloud.com:443";

    // 构造设备影子查询URL（华为云属性查询接口）
    QString url = QString("%1/v5/iot/%2/devices/%3/shadow")
                  .arg(baseUrl).arg(projectId).arg(deviceId);

    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setRawHeader("X-Auth-Token", Token);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    // 保存回调函数到临时变量（用于异步处理）
    currentCallback = callback;

    // 标记当前操作为属性查询
    function_select = 0; // 与原代码逻辑保持一致

    // 发送GET请求
    manger->get(request);
}

void MainWindow::onRefreshPropertiesClicked()
{
    getDeviceProperties([this](const QJsonObject& properties, int statusCode) {
        if (statusCode == 200) {
            // 解析属性数据（参考原逻辑）
            if (properties.contains("shadow")) {
                QJsonArray shadowArray = properties["shadow"].toArray();
                for (const auto& item : shadowArray) {
                    QJsonObject reported = item.toObject()["reported"].toObject();
                    float temp = reported["properties"].toObject()["DHT11_T"].toDouble();
                    int hm = reported["properties"].toObject()["DHT11_H"].toInt() - 20;
                    int ill = reported["properties"].toObject()["BH1750"].toInt();
                    m_HandWidget->n_tm =  temp;
                    m_HandWidget->n_hm = hm;
                    m_HandWidget->n_ill = ill;
                    static double time = 0;
                    time += 1;

                    my_table->addDataPoint(time, temp, hm, ill);

                    if(temp > dd.setTemp){
                        //QMessageBox::warning(this,"警告！！！","温度过高，已自动开始降温",QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel,QMessageBox::Yes);
                    }
                    if(hm > dd.setHum){
                       // QMessageBox::warning(this,"警告！！！","湿度过高，已自动开始除湿",QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel,QMessageBox::Yes);
                    }
                    if(ill > dd.setillum){
                        //QMessageBox::warning(this,"警告！！！","光照强度过高，已自动开始降低光照",QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel,QMessageBox::Yes);
                    }
                }
            }
        } else {
            qWarning() << "查询失败:" << properties["error_msg"].toString();
        }
    });
}

void MainWindow::saveTokenToFile(const QByteArray& token)
{
    QDir().mkpath(QFileInfo(TOKEN_FILE).path()); // 确保目录存在

    QFile file(TOKEN_FILE);
    if (file.open(QIODevice::WriteOnly)) {
        QDataStream out(&file);
        out << token; // 二进制写入
        file.setPermissions(QFile::ReadOwner | QFile::WriteOwner); // 设置文件权限
        qDebug() << "Token saved to:" << TOKEN_FILE;
    } else {
        qWarning() << "Save failed:" << file.errorString();
    }
}

QByteArray MainWindow::loadTokenFromFile()
{
    QFile file(TOKEN_FILE);
    if (!file.exists()) return QByteArray(); // 文件不存在返回空

    if (file.open(QIODevice::ReadOnly)) {
        QDataStream in(&file);
        QByteArray token;
        in >> token; // 二进制读取
        return token;
    }
    return QByteArray();
}

void MainWindow::replyFinished(QNetworkReply *reply)
{
    QString displayInfo;
    int statusCode=reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    QByteArray replyData =reply->readAll();

    if (function_select == 0) {
        QJsonObject result;
        if (statusCode == 200) {
            QJsonParseError jsonError;
            QJsonDocument doc = QJsonDocument::fromJson(replyData, &jsonError);
            if (jsonError.error == QJsonParseError::NoError && doc.isObject()) {
                result = doc.object(); // 返回完整JSON响应
            } else {
                result["error"] = "JSON解析失败";
            }
        } else {
            result["error_code"] = QString::number(statusCode);
            result["error_msg"] = QString(replyData);
        }

        // 触发回调（返回数据 + 状态码）
        if (currentCallback) {
            currentCallback(result, statusCode);
        }
        return; // 结束处理
    }

    //更新token
    if(function_select==3)
    {
       displayInfo="token 更新失败";
       QList<QNetworkReply::RawHeaderPair> RawHeader=reply->rawHeaderPairs();
       qDebug()<< "HTTP响应头应数量："<< RawHeader.size();
       qDebug()<<"RawHeader:"<< RawHeader;

       for(int i=0;i<RawHeader.size();i++)
       {
          QString first=RawHeader.at(i).first;
          QString second=RawHeader.at(i).second;
          if(first=="X-Subject-Token")
          {
             Token=second.toUtf8();
             displayInfo="token 更新成功.";
             //保存到文件
             saveTokenToFile(Token);
             break;
         }
       }
       QMessageBox::information(this,"提示",displayInfo,QMessageBox::Ok,QMessageBox::Ok);
       return;
    }

    //判断状态码
    if(200 != statusCode)
    {
        //解析数据
        QJsonParseError json_error;
        QJsonDocument document = QJsonDocument::fromJson(replyData,&json_error);
        if(json_error.error == QJsonParseError::NoError)
        {
            //判断是否是对象，然后开始解析数据
            if(document.isObject())
            {
                QString error_str="";
                QJsonObject obj = document.object();
                QString error_code;
                //解析错误代码
                if(obj.contains("error_code"))
                {
                    error_code = obj.take("error_code").toString();

                    //身份验证失败
                    if(error_code=="IOTDA.000002")
                    {
                        //显示错误代码
                        QMessageBox::information(this,"提示","身份验证失败.\n先点击<更新Token>按钮",QMessageBox::Ok,QMessageBox::Ok);
                        return;
                    }
                    //设备不在线
                    else if(error_code == "IOTDA.014016")
                    {
                        //显示错误代码
                        QMessageBox::information(this,"提示","设备未在线!\n无法下命令",QMessageBox::Ok,QMessageBox::Ok);
                        return;
                    }
                    else
                    {
                        error_str+="错误代码";
                        error_str+=error_code;
                        error_str+="\n";
                    }

                    //显示错误代码
                    QMessageBox::information(this,"提示",error_str,QMessageBox::Ok,QMessageBox::Ok);
                }
            }
            return;
        }
        //设置属性
        if(function_select==12 || function_select==13)
        {
            //解析数据
            QJsonParseError json_error;
            QJsonDocument document = QJsonDocument::fromJson(replyData,&json_error);
            if(json_error.error == QJsonParseError::NoError)
            {
                //判断是否是对象，然后开始解析数据
                if(document.isObject())
                {
                    QJsonObject obj = document.object();
                    if(obj.contains("response"))
                    {
                        QJsonObject obj1=obj.take("response").toObject();
                        int val = 0;
                        QString success;
                        if(obj1.contains("result_code"))
                        {
                            val=obj1.take("result_code").toInt();
                        }
                        if(obj1.contains("result_desc"))
                        {
                            success=obj1.take("result_desc").toString();
                        }

                        if(val==0 && success == "success")
                        {
                            //显示状态
                            QMessageBox::information(this,"提示","远程命令操作完成",QMessageBox::Ok,QMessageBox::Ok);
                            return;
                        }
                        else
                        {
                            //显示状态
                            QMessageBox::information(this,"提示","设备未正确回应，请检测设备网络",QMessageBox::Ok,QMessageBox::Ok);
                            return;
                        }
                    }
                }
            }
        }
        //查询设备属性
        if(function_select == 0)
        {
            //解析数据
            QJsonParseError json_error;
            QJsonDocument document = QJsonDocument::fromJson(replyData,&json_error);
            if(json_error.error == QJsonParseError::NoError)
            {
                //判断是否是对象，然后开始解析数据
                if(document.isObject())
                {
                    QJsonObject obj = document.object();
                    if(obj.contains("shadow"))
                    {
                        QJsonArray array = obj.take("shadow").toArray();
                        for(int i = 0; i < array.size(); i++)
                        {
                            QJsonObject obj2=array.at(i).toObject();
                            if(obj2.contains("reported"))
                            {
                                QJsonObject obj3=obj2.take("reported").toObject();

                                if(obj3.contains("properties"))
                                {
                                    //提取时间
                                    QString event_time = obj3.take("event_time").toString();
                                    qDebug() << "event_time:" <<event_time;

                                    //解析时间字段为 QDateTime对线
                                    QDateTime dateTime = QDateTime::fromString(event_time,"yyyyMMddTHHmmssZ");

                                    //转换为北京时间
                                    dateTime.setTimeSpec(Qt::UTC);
                                    dateTime = dateTime.toLocalTime();

                                    //输出标准的时间格式
                                    QString update_time = dateTime.toString("yyyy-MM-dd HH:mm:ss");

                                    QJsonObject properties = obj3.take("properties").toObject();

                                    qDebug() << "开始解析数据";

                                    int DHT11_T; // 环境温度
                                    int DHT11_H; //环境湿度
                                    int DHT11_I; //光照强度

                                    //提取数据
                                    DHT11_T = properties.take("DHT11_T").toInt();
                                    DHT11_H = properties.take("DHT11_H").toInt();
                                    DHT11_I = properties.take("BH1750").toInt();

                                    //
                                    //放入界面
                                    //

                                    //---------------------------判断数据是否离线------------------------------
                                    //获取当前时间
                                    QDateTime currentDateTime = QDateTime::currentDateTime();

                                    //计算时间差
                                    qint64 secondsDiff = currentDateTime.secsTo(dateTime);
                                    if(qAbs(secondsDiff) >= 5*60)
                                    {
                                        qDebug() << "离线" << "时间差超过5分钟";
                                    }
                                    else
                                    {
                                        //在线
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return;
    }
}

/*******以上为HTTP连接华为云******/

void MainWindow::get_init()
{
    connect(m_HandWidget,&HandWidget::label_4_push,this,&MainWindow::fan_on);// 风扇开
    connect(m_HandWidget,&HandWidget::label_3_push,this,&MainWindow::fan_off);// 风扇关
    connect(m_HandWidget,&HandWidget::label_push, this, &MainWindow::led_on);   // LED开
    connect(m_HandWidget,&HandWidget::label_2_push, this, &MainWindow::led_off);// LED关
    connect(m_HandWidget,&HandWidget::label_5_push, this, &MainWindow::buzzer_on);
    connect(m_HandWidget,&HandWidget::label_6_push, this, &MainWindow::buzzer_off);

    connect(m_HandWidget,&HandWidget::label_18_push, this, [=](float m_tm){
        dd.setTemp = m_tm;
    });
    connect(m_HandWidget,&HandWidget::label_21_push, this, [=](float m_tm){
        dd.setTemp = m_tm;
    });
    connect(m_HandWidget,&HandWidget::label_22_push, this, [=](float m_hm){
        dd.setHum = m_hm;
    });
    connect(m_HandWidget,&HandWidget::label_23_push, this, [=](float m_hm){
        dd.setHum = m_hm;
    });
    connect(m_HandWidget,&HandWidget::label_7_push, this, [=](float m_ill){
        dd.setillum = m_ill;
    });
    connect(m_HandWidget,&HandWidget::label_17_push, this, [=](float m_ill){
        dd.setillum = m_ill;
    });
}


void MainWindow::led_on()
{
    QJsonObject contentObj;  // 创建JSON对象
    contentObj["operation"] = "led_on";  // 直接设置键值对
    sendMessageToDevice(contentObj);  // 传递JSON对象
}  // 开灯
void MainWindow::led_off()
{
    QJsonObject contentObj;  // 创建JSON对象
    contentObj["operation"] = "led_off";  // 直接设置键值对
    sendMessageToDevice(contentObj);  // 传递JSON对象
}  // 关灯
void MainWindow::fan_on()
{
    QJsonObject contentObj;  // 创建JSON对象
    contentObj["operation"] = "fan_on";  // 直接设置键值对
    sendMessageToDevice(contentObj);  // 传递JSON对象
}  // 开风扇
void MainWindow::fan_off()
{
    QJsonObject contentObj;  // 创建JSON对象
    contentObj["operation"] = "fan_off";  // 直接设置键值对
    sendMessageToDevice(contentObj);  // 传递JSON对象
}  // 关风扇
void MainWindow::buzzer_on()
{
    QJsonObject contentObj;  // 创建JSON对象
    contentObj["operation"] = "buzzer_on";  // 直接设置键值对
    sendMessageToDevice(contentObj);  // 传递JSON对象
}  // 开蜂鸣器
void MainWindow::buzzer_off()
{
    QJsonObject contentObj;  // 创建JSON对象
    contentObj["operation"] = "buzzer_off";  // 直接设置键值对
    sendMessageToDevice(contentObj);  // 传递JSON对象
}  // 关蜂鸣器

void MainWindow::db_init() {
    QString connectionName = "GreenOasisDB"; // 统一连接名
    if (!QSqlDatabase::contains(connectionName)) { // 避免重复创建
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", connectionName);
        QString dbPath = QCoreApplication::applicationDirPath() + "/object.db"; // 绝对路径
        db.setDatabaseName(dbPath);
        if (!db.open()) {
            qDebug() << "DB open error:";
            return;
        }
        QSqlQuery query(db);
        QString sql = "CREATE TABLE IF NOT EXISTS oasis ("
                      "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                      "temperature REAL, "
                      "humidity REAL, "
                      "illumination INTEGER);";
        if (!query.exec(sql)) {
            qDebug() << "Create table error:";
        }
        sql = "CREATE TABLE IF NOT EXISTS time ("
                "tm_time INTEGER DEFAULT 0, "
                "hm_time INTEGER DEFAULT 0, "
                "ill_time INTEGER DEFAULT 0);";
        if (!query.exec(sql)) {
            qDebug() << "Create table error:";
        }
    }
}


bool MainWindow::db_update()
{
    QSqlDatabase db = QSqlDatabase::database("GreenOasisDB");
    if (!db.isOpen()) {
        qDebug() << "Database not open!";
        return false;
    }

    QSqlQuery query(db);
    query.prepare("UPDATE oasis SET temperature=?, humidity=?, illumination=? WHERE id=?");
    query.addBindValue(dd.setTemp); // 直接绑定浮点数
    query.addBindValue(dd.setHum);
    query.addBindValue(dd.setillum);
    query.addBindValue(1);

    if (!query.exec()) {
        qDebug() << "Update error:";
        return false;
    }
    return true;
}
bool MainWindow::db_select()
{
    QSqlDatabase db = QSqlDatabase::database("GreenOasisDB");
    if (!db.isOpen()) {
        qDebug() << "Database not open!";
        return false;
    }

    QSqlQuery query(db);
    query.prepare("SELECT * FROM oasis WHERE id = ?");
    query.addBindValue(1);

    if (!query.exec()) {
        qDebug() << "Select error:";
        return false;
    }

    if (query.next()) {
        dd.setTemp = query.value("temperature").toFloat();
        dd.setHum = query.value("humidity").toInt();
        dd.setillum = query.value("illumination").toInt();
    }
    return true;
}

bool MainWindow::resetTimeTable()
{
    QSqlDatabase db = QSqlDatabase::database("GreenOasisDB");
    if (!db.isOpen()) {
        qDebug() << "Database not open!";
        return false;
    }

    QSqlQuery query(db);
    // 将time表中的三个时间字段清零
    QString sql = "UPDATE time SET tm_time = 0, hm_time = 0, ill_time = 0";
    if (!query.exec(sql)) {
        qDebug() << "Reset time table error:";
        return false;
    }

    // 同时重置内存中的时间变量
    tm_time = 0;
    hm_time = 0;
    ill_time = 0;

    // 更新HandWidget中的显示
    m_HandWidget->tm_time = 0;
    m_HandWidget->hm_time = 0;
    m_HandWidget->ill_time = 0;

    return true;
}

MainWindow::~MainWindow()
{
    db_update();

    m_timer.stop();

    QString connectionName = "GreenOasisDB";
    if (QSqlDatabase::contains(connectionName))
    {
        // 创建作用域确保db对象提前销毁
        {
            QSqlDatabase db = QSqlDatabase::database(connectionName);
            if(db.isOpen()) {
                db.close();  // 显式关闭连接
            }
        } // 此处db对象离开作用域被销毁

        // 确保所有关联对象销毁后再移除连接
        QSqlDatabase::removeDatabase(connectionName);
    }
    //this->close();
    delete ui;
}

void MainWindow::init()
{

    // 初始化导航栏按钮
    for(int i = 0 ; i<6;i++)
    {
        NavBtn* btn = new NavBtn(ui->widgetNav);
        btn->setMinimumWidth(110);
        btn->setIndex(i);
        switch (i) {
        case 0:
            btn->setPicName("border-image: url(:/new/prefix1/Resource/Nav2.png);",tr("监控画面"));
            btn->setClickedStyle();
            ui->stackedWidget->setCurrentIndex(0);
            break;
        case 1:
            btn->setPicName("border-image: url(:/new/prefix1/Resource/Nav3.png);",tr("环境调控"));
            break;
        case 2:
            btn->setPicName("border-image: url(:/new/prefix1/Resource/Nav4.png);",tr("适宜环境设置"));
            break;
        case 3:
            btn->setPicName("border-image: url(:/new/prefix1/Resource/Nav5.png);",tr("AI建议"));
            break;
        case 4:
            btn->setPicName("border-image: url(:/new/prefix1/Resource/Nav6.png);",tr("统计表格"));
            break;
        case 5:
            btn->setPicName("border-image: url(:/new/prefix1/Resource/Nav7.png);",tr("农场日记"));
            break;
        default:
            break;
        }

        m_NavBtnMap.insert(btn->getName(),btn);
        ui->verticalLayoutNav->addWidget(btn);

        connect(btn,&NavBtn::sigClicked,[=](QString name)
        {
            QMap<QString,NavBtn*>::Iterator item = m_NavBtnMap.begin();
            while (item != m_NavBtnMap.end()) {
                if(item.key() != name)
                {
                    ((NavBtn*)(item.value()))->setNormalStyle();
                }
                item++;
            }
            ui->stackedWidget->setCurrentIndex(m_NavBtnMap.value(name)->getIndex());
        });
       }



    ui->labelTime->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss").replace(" ","\n"));
    connect(&m_timer,&QTimer::timeout,[=]
    {
         ui->labelTime->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss").replace(" ","\n"));
         if(m_HandWidget->n_tm < m_ParamterWidget->high_tm && m_HandWidget->n_tm > m_ParamterWidget->low_tm){
             tm_time++;
             m_HandWidget->tm_time = tm_time;
         }
         if(m_HandWidget->n_hm < m_ParamterWidget->high_hm && m_HandWidget->n_hm > m_ParamterWidget->low_hm){
             hm_time++;
             m_HandWidget->hm_time = hm_time;
         }
         if(m_HandWidget->n_ill < m_ParamterWidget->high_ill && m_HandWidget->n_ill > m_ParamterWidget->low_ill){
             ill_time++;
             m_HandWidget->ill_time = ill_time;
         }
         //AI参考数据传输
         m_AIPredictionWidget->setEnvironmentData(
             m_HandWidget->tm_time,
             m_HandWidget->hm_time,
             m_HandWidget->ill_time
         );
    });
    connect(&m_timer_2,&QTimer::timeout,[=](){
        //获取设备数据
        onRefreshPropertiesClicked();
    });
    m_timer.start(1000);
    m_timer_2.start(2000);


   //初始化监控界面
    m_MonitorWidget = new MonitorWidget(ui->pageMonitor);
    ui->verticalLayoutMonitor->addWidget(m_MonitorWidget);
    //初始化手动界面
    m_HandWidget = new HandWidget(ui->pageHand);
    ui->verticalLayoutHandle->addWidget(m_HandWidget);
    //初始化设置界面
    m_ParamterWidget = new ParamterWidget(ui->pageParamter);
    ui->verticalLayoutParamter->addWidget(m_ParamterWidget);

    //AI界面
    m_AIPredictionWidget = new AIPredictionWidget();
    ui->stackedWidget->insertWidget(3, m_AIPredictionWidget);

    my_table = new Tabel;
    ui->stackedWidget->insertWidget(4, my_table);

    login_o = new oasis;
    ui->stackedWidget->insertWidget(5, login_o);

    my_weather = new WeatherWidget;
    ui->label_5->installEventFilter(this);

}

bool MainWindow::eventFilter(QObject *watched, QEvent *event) //过滤器
{
    if(watched == ui->label_5){
        if (event->type() == QEvent::MouseButtonPress){
                my_weather->show();
            }
            //return true;  //过滤
            return false; //不过滤
    }
}

